package service

import (
	"errors"
	"fmt"
	"gin-luban-server/global"
	"gin-luban-server/model"
	"gin-luban-server/model/request"
	"gin-luban-server/utils"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"gorm.io/gorm"
)

// 增
func CreateDomain(domain model.CMDBDomain) (err error) {
	if !errors.Is(global.GVA_DB.Where("domain_name = ? ", domain.DomainName).First(&model.CMDBDomain{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同域名!")
	}
	return global.GVA_DB.Create(&domain).Error
}

// 删
func DeleteDomain(id float64) (err error) {
	var domain model.CMDBDomain
	// 2. 删除
	err = global.GVA_DB.Where("id = ?", id).Delete(&domain).Error
	return err
}

// 改
func UpdateDomain(domain model.CMDBDomain) (err error) {
	var total int64
	var Domains []model.CMDBDomain
	err = global.GVA_DB.Where("domain_name = ? AND id != ?",domain.DomainName,domain.ID).Find(&Domains).Count(&total).Error
	if total >= 1 {
		return errors.New("存在相同域名!")
	}
	// 通过唯一ID进行更新
	err = global.GVA_DB.Where("id = ?", domain.ID).First(&model.CMDBDomain{}).Updates(&domain).Error
	return err
}

// 查
func FindDomainById(id float64) (err error, domain model.CMDBDomain) {
	err = global.GVA_DB.Preload("Project").Where("id = ?", id).First(&domain).Error
	return err, domain
}

// 查 获取域名列表
func GetCMDBDomainInfoList(domain model.CMDBDomain, info request.PageInfo, desc bool) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&model.CMDBDomain{})
	var DomainList []model.CMDBDomain

	if domain.DomainName != "" {
		db = db.Where("domain_name LIKE ?", "%"+domain.DomainName+"%")
	}

	if domain.Protocol != "" {
		db = db.Where("protocol = ?", domain.Protocol)
	}

	if domain.ProjectCode != "" {
		db = db.Where("project_code = ?", domain.ProjectCode)
	}

	err = db.Count(&total).Error

	if err != nil {
		return err, DomainList, total
	} else {
		db = db.Limit(limit).Offset(offset)
		err = db.Preload("Project").Find(&DomainList).Error
	}
	return err, DomainList, total
}

// 导出excel
func ParseDomainInfoList2Excel(domain model.CMDBDomain, filePath string) error {

	db := global.GVA_DB.Model(&model.CMDBDomain{})
	var domainList []model.CMDBDomain

	if domain.DomainName != "" {
		db = db.Where("domain_name LIKE ?", "%"+domain.DomainName+"%")
	}

	if domain.Protocol != "" {
		db = db.Where("protocol = ?", domain.Protocol)
	}

	if domain.ProjectCode != "" {
		db = db.Where("project_code = ?", domain.ProjectCode)
	}


	err := db.Preload("Project").Find(&domainList).Error
	if err != nil {
		return err
	}
	// 写入 excel文件
	excel := excelize.NewFile()
	excel.SetSheetRow("Sheet1","A1",&[]string{"ID", "域名", "协议", "域名首页", "环境",
		"外网IP","外网端口", "内网IP","内网端口", "ICP备案号", "公安备案号", "过期时间", "所属项目", "状态"})
	for i, menu := range domainList {
		axis := fmt.Sprintf("A%d",i+2)
		excel.SetSheetRow("Sheet1",axis,&[]interface{}{
			menu.ID,
			menu.DomainName,
			menu.Protocol,
			menu.DomainIndex,
			menu.Env,
			menu.ExternalIp,
			menu.ExternalPort,
			menu.InternalIp,
			menu.InternalPort,
			menu.ICPNumber,
			menu.GANumber,
			menu.ExpireTime.Format("2006-01-02"),  // 要转成字符串 写入excel
			menu.Project.ProjectName,
			utils.BoolToString(*menu.Status),      // 布尔值转成 字符串 正常|关闭
		})
	}
	fmt.Printf("保存到execl....\n")
	excel.SaveAs(filePath)
	return nil
}

